package com.xxtx.trade.sysUser.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xxtx.trade.agent.bean.TradeSysAgent;
import com.xxtx.trade.agent.dto.ImeiToPhoneDto;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.enums.ExportEnum;
import com.xxtx.trade.common.util.IdCreateUtil;
import com.xxtx.trade.common.util.SpringUserContext;
import com.xxtx.trade.common.util.model.PageInfo;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.sysUser.dto.*;
import com.xxtx.trade.sysUser.enums.TradeSysUserEnum;
import com.xxtx.trade.sysUser.service.TradeExportService;
import com.xxtx.trade.sysUser.service.TradeSysUserService;
import com.xxtx.trade.sysUser.vo.ImeiToPhoneVO;
import com.xxtx.trade.sysUser.vo.TradeSysUserVo;
import com.xxtx.trade.thread.DownloadAdminSimThread;
import com.xxtx.trade.thread.DownloadBaiduInfoThread;
import com.xxtx.trade.thread.DownloadKuaiShouInfoThread;
import com.xxtx.trade.thread.DownloadTencentInfoThread;
import com.xxtx.trade.web.userCenter.SysTiktokController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TradeExportServiceImpl implements TradeExportService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysTiktokController.class);

    @Autowired
    private SpringUserContext springUserContext;
    @Autowired
    private TradeSysAgentMapper tradeSysAgentMapper;

    @Autowired
    private TradeSysUserService tradeSysUserService;

    @Autowired
    private FieldManageMapper fieldManageMapper;


    @Override
    public Result selectDownLoadList(TradeSysUserDto dto) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            TradeSysAgent agent = tradeSysAgentMapper.selectAgentByAccountId(loginUser.getId());
            if (agent != null) {
                dto.setLoginUserId(loginUser.getId());
            }
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "createTime desc");
            List<Map<String, Object>> list = tradeSysAgentMapper.selectDownLoadSim(dto);
            for (Map<String, Object> map : list) {
                map.put("stateName", ExportEnum.description(Integer.valueOf(String.valueOf(map.get("state")))));
                map.put("createTime", format.format(map.get("createTime")));
                if ((int) map.get("state") != (ExportEnum.WAITING.getCode())) {
                    map.put("endTime", format.format(map.get("endTime")));
                }
            }
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            return Result.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询异常");
    }


    /**
     * wzyk修改版：excel导出
     */
    @Override
    public Result allUrlInfos(TradeSysRoleDto form) {

        /**
         * form 对象内容：非管理员使用则全为空，需主动装配参数
         * */

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddMddmmsss");
        String parse = format.format(new Date());
        //根据当前登录用户获取信息
        TradeSysUserVo currentLoginUser = springUserContext.getCurrentLoginUser();
        // form装配userid，用于辨别执行下载操作的用户
        form.setUserId(currentLoginUser.getId());

        //非管理员用户，不必要，currentLoginUser可直接获得当前用户的 agent_id = currentLoginUser.getAgentId();
        if (!currentLoginUser.getRoles().get(0).getId().equals(TradeSysUserEnum.ROLE_MANAGER_ID.getCode())) {
            String agentId = currentLoginUser.getAgentId();
            // 把agentId装载到里面
            form.setAgentId(agentId);
        }

        // 获取 info 总数
        Integer countSize = tradeSysAgentMapper.selectCountAllUrlsBy(form);

        // 后一个参数是1代表装配抖音数据字段参数
        // 后一个参数是2代表装配腾讯数据字段参数
        // 只有非管理员才需要装配各字段状态
        form = tradeSysUserService.setTradeSysRoleDto(form);

        String id = IdCreateUtil.getId();
        String url = parse + "链接数据下载.xlsx";

        // 创建线程
        DownloadAdminSimThread thread = new DownloadAdminSimThread();
        thread.setCount(countSize);
        thread.setUrl(url);

        // 添加userId
        thread.setUserId(form.getUserId());


        thread.setId(id);
        thread.setType(1);
        thread.setTradeSysRoleDto(form);
        if (form.getUser_role().equals("2")){
            thread.setAgentId(form.getAgentId());
        }else {
            thread.setAgentId(currentLoginUser.getAgentId());

        }


        // 开启线程生成 excel
        new Thread(thread).start();


        // 生成下载记录
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("createTime", new Date());
        map.put("exportName", "抖音链接数据下载");
        map.put("state", 0);
        map.put("userId", currentLoginUser.getId());
        map.put("userName", currentLoginUser.getNickName());
        map.put("exportUrl", url);
        tradeSysAgentMapper.insertDownLog(map);
        return Result.success();
    }

    /**
     * 腾讯数据导出
     * */
    @Override
    public Result allTencentInfos(TradeSysRoleDto form) {
        /**
         * form 对象内容：非管理员使用则全为空，需主动装配参数
         * */
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddMddmmsss");
        String parse = format.format(new Date());
        //根据当前登录用户获取信息
        TradeSysUserVo currentLoginUser = springUserContext.getCurrentLoginUser();
        // form装配userid，用于辨别执行下载操作的用户
        form.setUserId(currentLoginUser.getId());

        //非管理员用户，不必要，currentLoginUser可直接获得当前用户的 agent_id = currentLoginUser.getAgentId();
        if (!currentLoginUser.getRoles().get(0).getId().equals(TradeSysUserEnum.ROLE_MANAGER_ID.getCode())) {
            String agentId = currentLoginUser.getAgentId();
            // 把agentId装载到里面
            form.setAgentId(agentId);
        }

        // 获取 info 总数
        Integer countSize = tradeSysAgentMapper.selectCountAllTencentUrlsBy(form);

        // 只有非管理员才需要装配各字段状态
        TencentInfoDto t_dto = new TencentInfoDto();
        t_dto.setUser_role(form.getUser_role());
        t_dto = tradeSysUserService.setTradeSysRoleDto(t_dto);

        String id = IdCreateUtil.getId();
        String url = parse + "链接数据下载.xlsx";

        // 创建线程
//        DownloadAdminSimThread thread = new DownloadAdminSimThread();
        DownloadTencentInfoThread thread = new DownloadTencentInfoThread();
        thread.setCount(countSize);
        thread.setUrl(url);
        thread.setTradeSysRoleDto(form);
        thread.setTencentInfoDto(t_dto);

        // 添加角色
        thread.setRole_id(t_dto.getUser_role());

        thread.setId(id);
        thread.setType(1);
        if (t_dto.getUser_role().equals("2")){
            thread.setAgentId(t_dto.getAgentId());
        }else {
            thread.setAgentId(currentLoginUser.getAgentId());
        }

        // 开启线程生成 excel
        new Thread(thread).start();


        // 生成下载记录
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("createTime", new Date());
        map.put("exportName", "腾讯链接数据下载");
        map.put("state", 0);
        map.put("userId", currentLoginUser.getId());
        map.put("userName", currentLoginUser.getNickName());
        map.put("exportUrl", url);
        tradeSysAgentMapper.insertDownLog(map);
        return Result.success();
    }

    @Override
    public Result allBaiduInfos(TradeSysRoleDto form) {
        /**
         * form 对象内容：非管理员使用则全为空，需主动装配参数
         * */
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddMddmmsss");
        String parse = format.format(new Date());
        //根据当前登录用户获取信息
        TradeSysUserVo currentLoginUser = springUserContext.getCurrentLoginUser();
        // form装配userid，用于辨别执行下载操作的用户
        form.setUserId(currentLoginUser.getId());
        //非管理员用户，不必要，currentLoginUser可直接获得当前用户的 agent_id = currentLoginUser.getAgentId();
        if (!currentLoginUser.getRoles().get(0).getId().equals(TradeSysUserEnum.ROLE_MANAGER_ID.getCode())) {
            String agentId = currentLoginUser.getAgentId();
            // 把agentId装载到里面
            form.setAgentId(agentId);
        }
        // 获取info总数
        Integer countSize = tradeSysAgentMapper.selectCountAllBaiduUrlsBy(form);

        // 只有非管理员才需要装配各字段状态
        BaiDuInfoDto baiDuInfoDto = tradeSysUserService.setBaiDuInfoDto(form);

        String id = IdCreateUtil.getId();
        String url = parse + "链接数据下载.xlsx";

        // 创建线程
        DownloadBaiduInfoThread thread = new DownloadBaiduInfoThread();
        thread.setCount(countSize);
        thread.setUrl(url);
        thread.setBaiDuInfoDto(baiDuInfoDto);

        thread.setId(id);
        thread.setType(1);

        //开启线程下载 excel
        new Thread(thread).start();

        //生成下载记录
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("createTime", new Date());
        map.put("exportName", "百度数据下载");
        map.put("state", 0);
        map.put("userId", currentLoginUser.getId());
        map.put("userName", currentLoginUser.getNickName());
        map.put("exportUrl", url);
        tradeSysAgentMapper.insertDownLog(map);
        return Result.success();
    }

    @Override
    public Result allKuaishouInfos(TradeSysRoleDto form) {
        /**
         * form 对象内容：非管理员使用则全为空，需主动装配参数
         * */
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddMddmmsss");
        String parse = format.format(new Date());
        // 根据当前登录用户获取信息
        TradeSysUserVo currentLoginUser = springUserContext.getCurrentLoginUser();
        //非管理员用户，不必要，currentLoginUser可直接获得当前用户的 agent_id = currentLoginUser.getAgentId();
        if (!currentLoginUser.getRoles().get(0).getId().equals(TradeSysUserEnum.ROLE_MANAGER_ID.getCode())) {
            String agentId = currentLoginUser.getAgentId();
            // 把agentId装载到里面
            form.setAgentId(agentId);
        }
        // 获取 info 总数
        Integer countSize = tradeSysAgentMapper.selectCountAllKSUrlsBy(form);

        // 只有非管理员才需要装配各字段状态
        KuaiShouInfoDto kuaiShouInfoDto = tradeSysUserService.setKuaiShouDto(form);

        String id = IdCreateUtil.getId();
        String url = parse + "链接数据下载.xlsx";

        // 创建线程
        DownloadKuaiShouInfoThread thread = new DownloadKuaiShouInfoThread();
        thread.setCount(countSize);
        thread.setUrl(url);
        thread.setKuaiShouInfoDto(kuaiShouInfoDto);

        thread.setId(id);
        thread.setType(1);

//        开启线程下载 excel
        new Thread(thread).start();

        //生成下载记录
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("createTime", new Date());
        map.put("exportName", "快手数据下载");
        map.put("state", 0);
        map.put("userId", currentLoginUser.getId());
        map.put("userName", currentLoginUser.getNickName());
        map.put("exportUrl", url);
        tradeSysAgentMapper.insertDownLog(map);
        return Result.success();
    }


///**
// * 原始版本
// */
//    @Override
//    public Result allUrlInfos(TradeSysRoleDto form) {
//        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddMddmmsss");
//        String parse = format.format(new Date());
//        //根据当前登录用户获取信息
//        TradeSysUserVo currentLoginUser = springUserContext.getCurrentLoginUser();
//
//        //非管理员用户
//        if (!currentLoginUser.getId().equals(TradeSysUserEnum.ROLE_MANAGER_ID.getCode())) {
//            String agentId = currentLoginUser.getAgentId();
//        }
//        Integer countSize=tradeSysAgentMapper.selectCountAllUrlsBy(form);
//
//        String id = IdCreateUtil.getId();
//        String url = parse + "链接数据下载.CSV";
//        DownloadAdminSimThread thread = new DownloadAdminSimThread();
//        thread.setCount(countSize);
//        thread.setUrl(url);
//        thread.setId(id);
//        thread.setType(1);
//        thread.setTradeSysRoleDto(form);
//        thread.setAgentId(currentLoginUser.getAgentId());
//        new Thread(thread).start();
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("id", id);
//        map.put("createTime",new Date());
//        map.put("exportName","链接数据下载");
//        map.put("state",0);
//        map.put("userId",currentLoginUser.getId());
//        map.put("userName",currentLoginUser.getNickName());
//        map.put("exportUrl",url);
//        tradeSysAgentMapper.insertDownLog(map);
//        return Result.success();
//    }



    // 用户上传的 imei 和 phone 对照excel表
    @Override
    public Result uploadImeiToPhone(List<ImeiToPhoneVO> excelVOS){

        ImeiToPhoneDto imeiToPhoneDto = new ImeiToPhoneDto();
        for (ImeiToPhoneVO imeiToPhoneVO: excelVOS){
            if (imeiToPhoneVO.getImei()==null)continue;
            if (imeiToPhoneVO.getPhone()==null)continue;
            ///^(?:(?:\+|00)86)?1[3-9]\d{9}$/
            if (!imeiToPhoneVO.getPhone().matches("^(?:(?:\\+|00)86)?1[3-9]\\d{9}$"))continue;
            imeiToPhoneDto.setImei(imeiToPhoneVO.getImei());
            if(fieldManageMapper.selectImeiToPhone(imeiToPhoneDto)!=null){
                // 如果说是存在的
                imeiToPhoneDto.setPhone(imeiToPhoneVO.getPhone());
                fieldManageMapper.setImeiPhone(imeiToPhoneDto);
            }else {
                imeiToPhoneDto.setPhone(imeiToPhoneVO.getPhone());
                fieldManageMapper.addImeiToPhone(imeiToPhoneDto);
            }
        }
        return Result.success();
    }



}
